var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var sass = require('gulp-sass');
var cleancss = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var pump = require('pump');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync');
var yargs = require('yargs').argv;

var SRC = __dirname + '/src';
var SRC_HTML = SRC + '/html/*.html';
var SRC_SASS = SRC + '/scss/*.scss';
var SRC_CSS = SRC + '/*.css';
var SRC_JS = SRC + '/**/*.js';

var BUILD = __dirname + '/build';
var BUILD_HTML = BUILD + '/html/';
var BUILD_CSS = BUILD + '/';
var BUILD_JS = BUILD + '/';

gulp.task('build:html', function () {
    gulp.src(SRC_HTML)
        .pipe(htmlmin({
            collapseInlineTagWhitespace: true,
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(BUILD_HTML))
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('build:sass', function () {
    gulp.src(SRC_SASS)
        .pipe(sourcemaps.init())
        .pipe(sass({ outputStyle: 'compressed' }).on('error', function (e) {
            console.log(e.message);
            this.emit('end');
        }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(SRC))
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('build:css', ['build:sass'], function() {
    gulp.src(SRC_CSS)
        .pipe(sourcemaps.init())
        .pipe(cleancss({ debug: true }, function (details) {
            console.log(details.name + ': ' + details.stats.originalSize);
            console.log(details.name + ': ' + details.stats.minifiedSize);
        }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(BUILD_CSS))
        .pipe(browserSync.reload({ stream: true }));
});

gulp.task('build:js', function(cb) {
    pump([
            gulp.src(SRC_JS),
            uglify(),
            gulp.dest(BUILD_JS),
            browserSync.reload({ stream: true })
        ],
        cb
      );
});

gulp.task('build', ['build:html', 'build:css', 'build:js']);

gulp.task('watch', function() {
    gulp.watch(SRC_HTML, ['build:html']);
    gulp.watch(SRC_SASS, ['build:css']);
    gulp.watch(SRC_JS, ['build:js']);
});


gulp.task('server', function () {
    yargs.p = yargs.p || 8080;
    browserSync.init({
        server: {
            baseDir: './build'
        },
        ui: {
            port: yargs.p + 1,
            weinre: {
                port: yargs.p + 2
            }
        },
        port: yargs.p,
        startPath: '/html/tenant.html'
    });
});

// 参数说明
//  -w: 实时监听
//  -s: 启动服务器
//  -p: 服务器启动端口，默认8080
gulp.task('default', ['build', 'server'], function() {
    if (yargs.s) {
        gulp.start('server');
    }

    if (yargs.w) {
        gulp.start('watch');
    }
});
